package hot100;

import DTO.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class levelOrder {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        if(root == null) {
            return ret;
        }
        //queue来存储同级节点
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            //记录当前层级节点
            List<Integer> level = new ArrayList<>();
            //统计当前层级节点的个数
            int curLevel = queue.size();

            for(int i = 0;i < curLevel;i++) {
                TreeNode node = queue.poll();
                level.add(node.val);

                //添加同级节点到queue中
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
            }
            //添加各层级节点
            ret.add(level);
        }
        return ret;

    }
}
